<?php


namespace App\Http\Controllers\Api\Repositories;


use App\Jobs\Circle\UpdateCircleCountJob;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxUserCircle;
use App\Models\Circle\WxCircle;
use App\Models\User\WxUser;
use App\Models\Circle\WxCircle as Model;
use App\Models\User\WxUserVisit;
use App\Models\WxPlate;
use App\Wen\Utils\CircleUtils;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\UserUtils;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


class WxCircleRepositores
{


    public static function add($data, $circle_state)
    {
        $model = new Model();
        global $__MINI_GLOBAL_TENANT_ID__;
        if ($data['id']) {
            $r = WxCircle::where('id', $data['id'])->update([
                'circle_name' => $data['circle_name'],
                'circle_introduce' => $data['circle_introduce'],
                'head_portrait' => $data['head_portrait'],
                'background_maps' => $data['background_maps'],
                'plate_id' => $data['plate_id'],
                'circle_state' => $circle_state
            ]);

            return $data['id'];
        } else {
            global $__MINI_GLOBAL_CURRENT_USER_ID__;
            if(_empty_($data['uid'])){
                $data['uid'] = $__MINI_GLOBAL_CURRENT_USER_ID__;
            }
            $model->circle_name = $data['circle_name'];
            $model->circle_introduce = $data['circle_introduce'];
            $model->head_portrait = $data['head_portrait'];
            $model->background_maps = $data['background_maps'];
            $model->plate_id = $data['plate_id'];
            $model->user_id = $data['uid'];
            $model->circle_state = $circle_state;
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                $model->tenant_id = $__MINI_GLOBAL_TENANT_ID__;
            }
            $r = $model->save();
            // (0审核中，1正常，2驳回)
            if($r){
                if($circle_state == 1){
                    UserUtils::add_user_notice(5001, $data['uid'], '圈子审核通知', '您的创建的圈子已经审核通过啦', 100);
                }else{
                    UserUtils::assistant_notice('admin', '有新的圈子创建申请待审核');
                }
            }
            return $model->id;
        }

    }

    /**
     * -1:最火;0:最新
     * @param $plateId
     * @return mixed
     */
    public static function circleByPlateId($plateId, $uid = 0)
    {
        global $__MINI_GLOBAL_TENANT_ID__;
        $data = null;
        if ($plateId == 0) {
            $query = (new Model())->where('circle_state', 1);
            $query->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__);
            $data = $query->withCount('wxPosts as posts_count')
                ->orderBy('created_at', 'DESC')
                ->limit(20)
                ->get();

        } elseif ($plateId == -1) {
            $query = (new Model())->where('circle_state', 1);
            $query->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__);
            $data = $query->withCount('wxPosts as posts_count')
                ->orderBy('sort', 'desc')
                ->limit(20)
                ->get();
        } elseif ($plateId == -2) {
            // 常用
            $object_ids = WxUserVisit::where([['user_id','=', $uid],['type', '=', 2]])->orderBy('updated_at', 'desc')->limit(100)->pluck('object_id');
            if($object_ids) {
                $query = (new Model())->whereIn('id', $object_ids)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $object_ids->toArray()) . '"' . ")"));
                $data = $query->withCount('wxPosts as posts_count')
                    ->orderBy('sort', 'desc')
                    ->limit(20)
                    ->get();
            }else{
                $data = [];
            }
        }else{
            $data =  (new Model())
                ->where('plate_id', $plateId)
                ->where('circle_state', 1)
                ->withCount('wxPosts as posts_count')
                ->orderBy('sort', 'desc')
                ->get();
        }

        if($data){
            $data->map(function ($v) use ($uid){
                $v->is_follow_circle = self::isFollowCircle($uid, $v->id);
                $v->can_i_visit = CircleUtils::can_i_visit($v, $uid);
                $v->user_circle_count = CircleUtils::circleFollowCount($v->id);
                return $v;
            });
            return $data;
        }
        return null;
    }

    /**
     * 搜索
     * @param $keyword
     * @return mixed
     */
    public static function searchCircle($keyword, $uid = 0, $limit = 10)
    {
        $data = (new Model())
            ->where('circle_state', 1)
            ->where(function ($query) use ($keyword) {
                $query->orWhere('circle_name', 'like', '%' . $keyword . '%')
                    ->orWhere('circle_introduce', 'like', '%' . $keyword . '%')
                    ->orWhere('id', $keyword);
            })
            ->withCount('wxPosts as posts_count')
            ->simplePaginate($limit);
        if($data){
            $data->map(function ($item) use ($uid) {
                $item->is_follow = (new WxUserCircle())->isFollowCircle($uid, $item->id);
                $item->user_circle_count = CircleUtils::circleFollowCount($item->id);
            });
            return $data;
        }
        return null;
    }

    /**
     * 推荐
     * @return mixed
     */
    public static function recommendCircle()
    {
        return (new Model())->where('circle_state', 1)->where('is_top_recommend', 1)->withCount('wxPosts as posts_count')->orderBy('sort', 'desc')->limit(4)->get();
    }

    /**
     * 热门
     * @return mixed
     */
    public static function hotCircle()
    {
        return (new Model())->where('circle_state', 1)->where('is_hot', 1)->orderBy('sort', 'desc')->limit(12)->get();
    }

    /**
     * 最新
     * @return mixed
     */
    public static function newCircle()
    {
        return (new Model())->where('circle_state', 1)->where('circle_state', 0)->limit(12)->orderBy('id', 'desc')->get();
    }

    /**
     * 全部
     * @param $page
     * @return mixed
     */
    public static function list($page)
    {
        return (new Model())->where('circle_state', 1)->where('circle_state', 0)->orderBy('id', 'desc')->paginate($page);
    }

    /**
     * 圈子文章组合(有的问题with limit)
     * @param $page
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function circleAndPost($limit = 10)
    {
        $data = (new Model())->where('circle_state', 1)
            ->withCount(['wxPosts as posts_count' => function ($query) {
                $query->where('is_examine', 1);
            }])
            ->orderBy('sort', 'desc')
            ->simplePaginate($limit);
        if($data){
            $data->map(function ($v, $k) {
                $data = WxPost::where('is_examine', 1)
                    ->where('posts_state', 0)
                    ->where('circle_id', $v->id)
                    ->orderBy('id', 'desc')
                    ->with(["user" => function ($query) {
                        $query->select(['id', 'user_avatar']);
                    }])->limit(3)
                    ->get(['id', 'posts_content', 'user_id', 'circle_id']);
                $data->map(function ($v) {
                    $v->commment_count = WxCommentRepositores::commentCount($v->id);
                    // 这里可以直接截取
                    $v->posts_content_raw = mb_substr(preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '',$v->posts_content), 0, 30);
                });
                $v->wx_posts = $data;
            });
            return $data;
        }
        return null;
    }

    /**
     * 用户关注圈子
     * @param $user_id
     * @param $circle_id
     * @param null $payment_duration 日期时间字符串
     * @return bool
     */
    public static function userFollowCircle($user_id, $circle_id, $payment_duration = null)
    {
        Cache::forget('circle:followCount:'.$circle_id);
        Cache::forget('circle:follow:users:'.$circle_id);
        UpdateCircleCountJob::dispatch($circle_id)->delay(now()->addSeconds(2));

        $model_obj = WxUserCircle::where('user_id', $user_id)->where('circle_id', $circle_id)->first();
        if ($model_obj) {
            if ($model_obj->user_circle_state == 1) {
                if ($payment_duration) {
                    WxUserCircle::where('user_id', $user_id)->where('circle_id', $circle_id)->update(['user_circle_state' => 0, 'payment_duration' => $payment_duration]);
                    return 0;
                } else {
                    WxUserCircle::where('user_id', $user_id)->where('circle_id', $circle_id)->update(['user_circle_state' => 0]);
                    return 0;
                }
            } else {
                if ($payment_duration) {
                    WxUserCircle::where('user_id', $user_id)->where('circle_id', $circle_id)->update(['user_circle_state' => 0, 'payment_duration' => $payment_duration]);
                    return 0;
                } else {
                    WxUserCircle::where('user_id', $user_id)->where('circle_id', $circle_id)->update(['user_circle_state' => 1]);
                    return 1;
                }
            }
        } else {
            DB::beginTransaction();
            try {
                $model = new WxUserCircle();
                $model->user_id = $user_id;
                $model->circle_id = $circle_id;
                if ($payment_duration) {
                    $model->payment_duration = $payment_duration;
                }
                $r = $model->save();
                if ($r) {
                    $user = WxUser::where('id', $user_id)->first(FieldUtils::userInfoColums());
                    $circle = WxCircle::where('id', $circle_id)->first(['id', 'user_id', 'circle_name']);
                    Redis::rpush('realtime:others:list', json_encode([$circle['user_id'], 4, 1]));
                    Redis::rpush('realtime:others:list', json_encode([$circle_id, 2, 1]));
                    UserUtils::add_user_notice(5002, $circle['user_id'], '创建的圈子收获粉丝', '「<a href="/pages/user/user?id='.$user_id.'">'.$user['user_name'].'</a>」' . '关注了你创建的「' . '<a href="/pages/circle/list?id='.$circle['id'].'">'.$circle['circle_name'].'</a>' . '」圈子。', 100);
                    UserUtils::add_user_experience($user_id, 6);
                    DB::commit();
                    return true;
                }
                DB::rollBack();
                return false;
            } catch (\Exception $e) {
                DB::rollBack();
                _logger_(__file__, __line__, $e->getMessage());
                return false;
            }
        }
    }

    /**
     * 用户关注的圈子文章组合列表
     * @param int $limit
     * @return \Illuminate\Contracts\Pagination\Paginator
     */
    public static function userFollowCircleList($uid, $limit = 10)
    {
        $userFollowCircle = WxUserCircle::where('user_id', $uid)->get();
        if($userFollowCircle){
            $circle_id_arr = [];
            foreach ($userFollowCircle as $k => $v) {
                $circle_id_arr[] = $v['circle_id'];
            }
            $data = (new Model())->where('circle_state', 1)
                ->whereIn('id', $circle_id_arr)
                ->withCount(['wxPosts as posts_count' => function ($query) {
                    $query->where('is_examine', 1);
                }])
                ->orderBy('sort', 'desc')
                ->simplePaginate($limit);
            $data->map(function ($v, $k) {
                $data = WxPost::where('is_examine', 1)
                    ->where('posts_state', 0)
                    ->where('circle_id', $v->id)
                    ->orderBy('id', 'desc')
                    ->with(["user" => function ($query) {
                        $query->select(['id', 'user_avatar']);
                    }])->limit(3)
                    ->get(['id', 'posts_content', 'user_id', 'circle_id']);
                $data->map(function ($v) {
                    $v->commment_count = WxCommentRepositores::commentCount($v->id);
                });
                $v->wx_posts = $data;
            });
            return $data;
        }
        return null;
    }

    /**
     * 获取圈子详细信息
     * @param $circle_id
     * @return mixed
     */
    public static function CircleInfo($circle_id)
    {
        $data = WxCircle::where('id', $circle_id)->first();
        if($data){
            if($data->circle_user_division > 0){
                $data->circle_user_division = $data->circle_user_division * 100;
            }
            if($data->circle_user_paycontent_division > 0){
                $data->circle_user_paycontent_division = $data->circle_user_paycontent_division * 100;
            }
            if($data){
                $data->append(['circle_user', 'circle_follow_count', 'circle_posts_count']);
                return $data;
            }
        }
        return null;
    }

    /**
     * 判断是否关注了该圈子
     */
    public static function isFollowCircle($uid, $circle_id = 0)
    {
        return WxUserCircle::where('user_id', $uid)
            ->where('circle_id', $circle_id)->where('user_circle_state', 0)->exists();
    }

    /**
     * 关注圈子
     * @param $uid
     * @param $circle_id
     * @return bool
     */
    public static function followCircle($uid, $circle_id)
    {
        $UserCircleModel = (new WxUserCircle());
        $UserCircleModel->user_id = $uid;
        $UserCircleModel->circle_id = $circle_id;
        return $UserCircleModel->save();
    }


}